package com.blyat.xsoft.kernel.component.mybatis.dialect;

import org.apache.ibatis.reflection.MetaObject;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author syh
 * @date 2019/11/8
 **/
public abstract class AbstractDialect implements Dialect {

    Pattern pattern = Pattern.compile(getSqlPattern(), Pattern.CASE_INSENSITIVE);

    @Override
    public String getEscapeString(String sql, MetaObject metaObject, Object obj) {
        if (!sql.toLowerCase().contains("like")) {
            return sql;
        }
        Matcher matcher = pattern.matcher(sql);

        Set<String> replaceEscape = new HashSet<>();
        Set<String> replaceFiled = new HashSet<>();

        while (matcher.find()) {
            replaceEscape.add(matcher.group());
            int n = matcher.groupCount();
            for (int i = 0; i <= n; i++) {
                String output = matcher.group(i);
                if (2 == i && output != null) {
                    replaceFiled.add(output.trim());
                }
            }
        }

        // 修改参数
        for (String key : replaceFiled) {
            if (!key.contains(".")) {
                Object val = metaObject.getValue(key);
                if (val != null && val instanceof String && (val.toString().contains("%") || val.toString().contains("_"))) {
                    val = val.toString().replaceAll("%", "/%").replaceAll("_", "/_");
                    metaObject.setValue(key, val);
                }
            } else {
                String[] keys = key.split(".");
                Object val = metaObject.getValue(keys[0]);
                if (val != null) {

                }
            }
        }

        return modifySql(sql, replaceEscape);
    }

    protected abstract String getSqlPattern();

    protected String modifySql(String sql, Set<String> replaceEscape) {
        for (String s : replaceEscape) {
            sql = sql.replace(s, s + " ESCAPE '/' ");
        }
        return sql;
    }
}
